/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
function updateClock ()
{
    var currentTime = new Date();
  
    var currentDay = currentTime.getDay();
    currentDay = ( currentDay == 0 ) ? "Sunday" : currentDay;
    currentDay = ( currentDay == 1 ) ? "Monday" : currentDay;
    currentDay = ( currentDay == 2 ) ? "Tuesday" : currentDay;
    currentDay = ( currentDay == 3 ) ? "Wednesday" : currentDay;
    currentDay = ( currentDay == 4 ) ? "Thursday" : currentDay;
    currentDay = ( currentDay == 5 ) ? "Friday" : currentDay;
    currentDay = ( currentDay == 6 ) ? "Saturday" : currentDay;

    var currentMonth = currentTime.getMonth();
    currentMonth = ( currentMonth == 0 ) ? "January" : currentMonth;
    currentMonth = ( currentMonth == 1 ) ? "February" : currentMonth;
    currentMonth = ( currentMonth == 2 ) ? "March" : currentMonth;
    currentMonth = ( currentMonth == 3 ) ? "April" : currentMonth;
    currentMonth = ( currentMonth == 4 ) ? "May" : currentMonth;
    currentMonth = ( currentMonth == 5 ) ? "June" : currentMonth;
    currentMonth = ( currentMonth == 6 ) ? "July" : currentMonth;
    currentMonth = ( currentMonth == 7 ) ? "August" : currentMonth;
    currentMonth = ( currentMonth == 8 ) ? "September" : currentMonth;
    currentMonth = ( currentMonth == 9 ) ? "October" : currentMonth;
    currentMonth = ( currentMonth == 10) ? "November" : currentMonth;
    currentMonth = ( currentMonth == 11) ? "December" : currentMonth;

    var currentDate = currentTime.getDate();
    currentDate = ( currentDate == 1 || currentDate == 21 || currentDate == 31 ) ? currentDate + "st" : currentDate;
    currentDate = ( currentDate == 2 || currentDate == 22 ) ? currentDate + "nd" : currentDate;
    currentDate = ( currentDate == 3 ) || currentDate == 23 ? currentDate + "rd" : currentDate;
    currentDate = ( currentDate > 3 || currentDate < 21 || currentDate > 23 || currentDate < 31 ) ? currentDate + "th" : currentDate;

    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();
    currentSeconds = (currentSeconds < 10 ? "0" : "") +currentSeconds;
    currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
    var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
    currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
    currentHours = ( currentHours == 0 ) ? 12 : currentHours;
    var currentTimeString = currentDay + ", " + currentMonth +  " " + currentDate + ", "+ currentTime.getFullYear();
    var currentTime1 = currentHours + ":" + currentMinutes + ":"+ currentSeconds +" "+ timeOfDay;
    $('span#date').html(currentTimeString);
    $('span#time').html(currentTime1);
}//end of updateClock
function cloneTableRow(elementId){
    var row = $("#"+ elementId +" tbody>tr:last").clone(true);
    clearForm(row);
    row.insertAfter("#"+elementId+" tbody>tr:last");
}//end of cloneTableRow
function clearTable(elementId){
    if(document.getElementById(elementId)!=null){
        while($("#"+elementId+" tr").length > 2){
            $("#"+ elementId +" tbody>tr:last").remove(); 
        }
    }
}//end of deleteTableRow
function clearForm(form) {
    // iterate over all of the inputs for the form
    // element that was passed in
    $(':input', form).each(function() {
        var type = this.type;
        //            alert(this.name);
        var tag = this.tagName.toLowerCase(); // normalize case
        // it's ok to reset the value attr of text inputs,
        // password inputs, and textareas
        if (type == 'text' || type == 'password' || tag == 'textarea'){
            this.value = "";
        // checkboxes and radios need to have their checked state cleared
        // but should *not* have their 'value' changed
        }else if (type == 'checkbox' || type == 'radio'){
            this.checked = false;
        // select elements need to have their 'selectedIndex' property set to -1
        // (this works for both single and multiple select elements)
        }else if (tag == 'select'){
            this.selectedIndex = 0;
        }else if (type == 'hidden'){
            this.value = "0";
        }
        if($(this).hasClass("hasDatepicker")){
            var this_id = $(this).attr("id"); // current inputs id
            var new_id = this_id +1; // a new id
            $(this).attr("id", new_id); // change to new id
            //                $(this).attr("changeYear", "true"); 
            //                $(this).attr("changeMonth", "true"); 
            //                $(this).attr("yearRange", "-70:+50"); 
            $(this).removeClass('hasDatepicker'); // remove hasDatepicker class
            $(this).datepicker({
                changeYear:true,
                changeMonth:true,
                yearRange:'-70:+50'
            }); // re-init datepicker
        }
    });
}//end of clear form
function setCheckbox(form, value) {
    // iterate over all of the inputs for the form
    // element that was passed in
    $(':input', form).each(function() {
        if (this.value == value){
            this.checked = true;
        }
    });
}//end of set check boxes
function updateTotals(){
    var businessTotalSales = 0;
    var totalCostofGoodsSold = 0;
    var grossMonthlyIncome = 0;        
    var totalOtherIncome = 0;
    var totalOperatingExpenses = 0;
    var totalFamilyExpenses = 0;
    var totalExpenses = 0;
    var netDisposableIncome =0;
    var totalEquipment = 0;
    var totalStocks=0;
    var totalStockWorth=0;
        
    var businessSales = ($("#businessSales1").val()=="") ? 0 : parseInt($("#businessSales1").val());
    var business2Sales = ($("#businessSales2").val()=="") ? 0 : parseInt($("#businessSales2").val());
    businessTotalSales = businessSales + business2Sales;
    $("#businessSalesTotal").val(businessTotalSales);
        
    var businessGoodsSold = ($("#businessGoodsSold1").val()=="") ? 0 : parseInt($("#businessGoodsSold1").val());
    var business2GoodsSold = ($("#businessGoodsSold2").val()=="") ? 0 : parseInt($("#businessGoodsSold2").val());
    totalCostofGoodsSold = businessGoodsSold + business2GoodsSold;
    $("#businessGoodsTotal").val(totalCostofGoodsSold);
        
    var businessGross = ($("#businessGross1").val()=="") ? 0 : parseInt($("#businessGross1").val());
    var business2Gross = ($("#businessGross2").val()=="") ? 0 : parseInt($("#businessGross2").val());
    grossMonthlyIncome = businessGross + business2Gross;
    $("#businessGrossTotal").val(grossMonthlyIncome);
        
    var totalIncomeEmployment = ($("#totalIncomeEmployment").val()=="") ? 0 : parseInt($("#totalIncomeEmployment").val());
    var totalInwardRemittance = ($("#totalInwardRemittance").val()=="") ? 0 : parseInt($("#totalInwardRemittance").val());
    var totalOthers = ($("#totalOthers").val()=="") ? 0 : parseInt($("#totalOthers").val());
    totalOtherIncome = totalIncomeEmployment + totalInwardRemittance + totalOthers;
    $("#totalOtherIncome").val(totalOtherIncome);
        
    var salariesAndWages = ($("#salariesAndWages").val()=="") ? 0 : parseInt($("#salariesAndWages").val());
    var rent = ($("#rent").val()=="") ? 0 : parseInt($("#rent").val());
    var utilities = ($("#utilities").val()=="") ? 0 : parseInt($("#utilities").val());
    var incidentalExpenses = ($("#incidentalExpenses").val()=="") ? 0 : parseInt($("#incidentalExpenses").val());
    var taxesAndLicenses = ($("#taxesAndLicenses").val()=="") ? 0 : parseInt($("#taxesAndLicenses").val());
    var transportation = ($("#transportation").val()=="") ? 0 : parseInt($("#transportation").val());
    var insurance = ($("#insurance").val()=="") ? 0 : parseInt($("#insurance").val());
    totalOperatingExpenses = salariesAndWages + rent + utilities + incidentalExpenses +
    taxesAndLicenses + transportation + insurance;
    $("#totalOperatingExpenses").val(totalOperatingExpenses);
        
    var familyRental = ($("#familyRental").val()=="") ? 0 : parseInt($("#familyRental").val());
    var familyUtilities = ($("#familyUtilities").val()=="") ? 0 : parseInt($("#familyUtilities").val());
    var familyFood = ($("#familyFood").val()=="") ? 0 : parseInt($("#familyFood").val());
    var familyClothing = ($("#familyClothing").val()=="") ? 0 : parseInt($("#familyClothing").val());
    var familyEducation = ($("#familyEducation").val()=="") ? 0 : parseInt($("#familyEducation").val());
    var familyMortgage = ($("#familyMortgage").val()=="") ? 0 : parseInt($("#familyMortgage").val());
    var familyMedicine = ($("#familyMedicine").val()=="") ? 0 : parseInt($("#familyMedicine").val());
    var familyInsurance = ($("#familyInsurance").val()=="") ? 0 : parseInt($("#familyInsurance").val());
    var familyOtherLoans = ($("#familyOtherLoans").val()=="") ? 0 : parseInt($("#familyOtherLoans").val());
    totalFamilyExpenses = familyRental + familyUtilities + familyFood + familyClothing +
    familyEducation + familyMortgage + familyMedicine + familyInsurance + familyOtherLoans;
    $("#totalFamilyExpenses").val(totalFamilyExpenses);
        
    totalExpenses = totalOperatingExpenses + totalFamilyExpenses;
    $("#totalExpenses").val(totalExpenses);
        
    netDisposableIncome = (grossMonthlyIncome + totalOtherIncome)- totalExpenses;
    $("#netDisposableIncome").val(netDisposableIncome);
        
    var equipment = ($("#equipment").val()=="") ? 0 : parseInt($("#equipment").val());
    totalEquipment = equipment;
    $("#totalEquipment").val(totalEquipment);
        
    var stocks = ($("#stocks").val()=="") ? 0 : parseInt($("#stocks").val());
    totalStocks = stocks;
    $("#totalStocks").val(totalStocks);
        
    var stockWorth = ($("#stockWorth").val()=="") ? 0 : parseInt($("#stockWorth").val());
    totalStockWorth = stockWorth;
    $("#totalStockWorth").val(totalStockWorth);
            

}//end update Monthly Statement totals
function populateDocumentInfo(json){
    //document
    if(json.document != null){
        $("#documentTypeId").val(json.document.documentTypeId);
        $("#documentNumber").val(json.document.documentNumber);
        $("#documentDate").val(json.document.documentDate);   
    }
    
}
function populateReferenceDocumentInfo(json){
    if(json.referenceDocument != null){
        //document
        $("#referenceTypeId").val(json.referenceDocument.documentTypeId);
        $("#referenceNumber").val(json.referenceDocument.documentNumber);
        $("#referenceDate").val(json.referenceDocument.documentDate);    
    }
}
function populateBorrowerInfo(json){
         
    $("#profilePhoto").attr("src",'images/profile/'+ json.borrower.borrowerId +'.jpg');
    $("#borrowerId").val(json.borrower.borrowerId);
    $("#oldBorrowerId").val(json.borrower.oldBorrowerId);
    $("#borrowerPlaceOfBirth").val(json.borrower.placeOfBirth);
    $("#borrowerCitizenship").val(json.borrower.citizenship);
    $("#borrowerContactNumber").val(json.borrower.contactNumber);
    $("#borrowerGender").val(json.borrower.gender);
    $("#borrowerReligion").val(json.borrower.religion);
    $("#borrowerDateOfBirth").val(json.borrower.dateOfBirth);
    $('#borrowerCivilStatus').val(json.borrower.civilStatus);
    $("#borrowerLastName").val(json.borrower.lastName);
    $("#borrowerMiddleName").val(json.borrower.middleName);
    $('#borrowerFirstName').val(json.borrower.firstName);
    $('#borrowerNickName').val(json.borrower.nickName)
    
    
    if(json.borrowerRelativeList != null && document.getElementById("spouseAndDependentsTable") !=null){
        clearTable("spouseAndDependentsTable");
        while($("#spouseAndDependentsTable tr").length - 1 < json.borrowerRelativeList.length){
            cloneTableRow("spouseAndDependentsTable");
        }
        if(json.borrowerRelativeList.length >0){
            $("#spouseAndDependentsTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="relativeId"]', element).val(json.borrowerRelativeList[index - 1].relativeId);
                    $('input[name="relativesFirstName"]', element).val(json.borrowerRelativeList[index - 1].firstName);
                    $('input[name="relativesMiddleName"]', element).val(json.borrowerRelativeList[index - 1].middleName);
                    $('input[name="relativesLastName"]', element).val(json.borrowerRelativeList[index - 1].lastName);
                    $('select[name="relativesRelationshipId"]', element).val(json.borrowerRelativeList[index - 1].relationshipId);
                    $('input[name="relativesOccupation"]', element).val(json.borrowerRelativeList[index - 1].occupation);
                    $('input[name="relativesDateOfBirth"]', element).val(json.borrowerRelativeList[index - 1].dateOfBirth);
                    $('input[name="relativesPlaceOfBirth"]', element).val(json.borrowerRelativeList[index - 1].placeOfBirth);
                    $('input[name="relativesCitizenship"]', element).val(json.borrowerRelativeList[index - 1].citizenship);
                    $('input[name="relativesMonthlyIncome"]', element).val(json.borrowerRelativeList[index - 1].monthlyIncome);
                }
            });
        }
    }
    if(document.getElementById("borrowersAddresstable") !=null){
        if($("#borrowersAddresstable tr").length == 3 && json.borrowerAddressList.length ==2){
            $("#borrowersAddresstable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="address"]', element).val(json.borrowerAddressList[index - 1].address);
                    $('input[name="postalCode"]', element).val(json.borrowerAddressList[index - 1].postalCode);
                    $('select[name="addressStatus"]', element).val(json.borrowerAddressList[index - 1].addressStatus);
                    $('select[name="addressAreaId"]', element).val(json.borrowerAddressList[index - 1].areaId);
                    $('select[name="yearsOfStay"]', element).val(json.borrowerAddressList[index - 1].yearsOfStay);
                }
            });
        }
    }
    if(document.getElementById("borrowerAddress") !=null && json.borrowerAddressList !=null){
        for(var index=0; index < json.borrowerAddressList.length; index++){
            if(json.borrowerAddressList[index].addressTypeId==1){
                $("#borrowerAddress").val(json.borrowerAddressList[index].address);
                $("#addressAreaId").val(json.borrowerAddressList[index].areaId);
            }
        }
    }
    
    if(json.businessList != null && document.getElementById("businessTable") !=null){
        clearTable("businessTable");
        while($("#businessTable tr").length - 1 < json.businessList.length){
            cloneTableRow("businessTable");
        }
        if(json.businessList.length > 0){
            $("#businessTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="businessId"]', element).val(json.businessList[index - 1].businessId);
                    $('input[name="businessName"]', element).val(json.businessList[index - 1].businessName);
                    $('input[name="businessType"]', element).val(json.businessList[index - 1].businessType);
                    $('input[name="businessAddress"]', element).val(json.businessList[index - 1].businessAddress);
                    $('input[name="businessAddressStatus"]', element).val(json.businessList[index - 1].businessAddressStatus);
                    $('input[name="businessExistence"]', element).val(json.businessList[index - 1].businessExistence);
                    $('input[name="businessAverageSale"]', element).val(json.businessList[index - 1].businessDailyAverageSales);
                    $('input[name="businessAmountOfStock"]', element).val(json.businessList[index - 1].businessStockAmount);
                }
            });
        }
    }
            
}//populate borrower info
function populateLoanApplicationBorrowerInfo(json){
         
    $("#profilePhoto").attr("src",'images/profile/'+ json.borrower.borrowerId +'.jpg');
    $("#borrowerId").val(json.borrower.borrowerId);
    $("#oldBorrowerId").val(json.borrower.oldBorrowerId);
    $("#borrowerLastName").val(json.borrower.lastName);
    $("#borrowerMiddleName").val(json.borrower.middleName);
    $('#borrowerFirstName').val(json.borrower.firstName);
    $("#borrowerDateOfBirth").val(json.borrower.dateOfBirth);
    $("#borrowerPlaceOfBirth").val(json.borrower.placeOfBirth);
    $("#borrowerGender").val(json.borrower.gender);
    $("#borrowerReligion").val(json.borrower.religion);
    $("#borrowerCitizenship").val(json.borrower.citizenship);
    $('#borrowerCivilStatus').val(json.borrower.civilStatus);
    $("#borrowerContactNumber").val(json.borrower.contactNumber);
    $("#borrowerEducationalAttainment").val(json.borrower.educationalAttainment);
    $("#borrowerOccupation").val(json.borrower.occupation);
    $("#borrowerMontlySalary").val(json.borrower.monthlySalary);
    $("#borrowerEmployer").val(json.borrower.employer);
    $("#borrowerEmployerPhoneNo").val(json.borrower.employerPhoneNo);
    $("#borrowerEmployerAddress").val(json.borrower.employerAddress);
    $('#borrowerNickName').val(json.borrower.nickName);    

    if(json.borrowerRelativeList != null && document.getElementById("dependentsTable") !=null){
        clearTable("dependentsTable");
        while($("#dependentsTable tr").length - 1 < json.borrowerRelativeList.length){
            cloneTableRow("dependentsTable");
        }
        if(json.borrowerRelativeList.length >0){
            $("#dependentsTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="relativeId"]', element).val(json.borrowerRelativeList[index - 1].relativeId);
                    $('input[name="relativesFirstName"]', element).val(json.borrowerRelativeList[index - 1].firstName);
                    $('input[name="relativesMiddleName"]', element).val(json.borrowerRelativeList[index - 1].middleName);
                    $('input[name="relativesLastName"]', element).val(json.borrowerRelativeList[index - 1].lastName);
                    $('input[name="relativesDateOfBirth"]', element).val(json.borrowerRelativeList[index - 1].dateOfBirth);
                    $('select[name="relativesRelationshipId"]', element).val(json.borrowerRelativeList[index - 1].relationshipId);
                    $('input[name="relativesAddress"]', element).val(json.borrowerRelativeList[index - 1].address);
                    $('input[name="relativesNameOfSchool"]', element).val(json.borrowerRelativeList[index - 1].nameOfSchool);
                }
            });
        }
    }
    if(document.getElementById("borrowersAddresstable") !=null && json.borrowerAddressList != null){
        if($("#borrowersAddresstable > tbody > tr > td").length == 3 && json.borrowerAddressList.length > 0 && json.borrowerAddressList.length <= 3){
            for(var index=0; index < json.borrowerAddressList.length; index++){
                var table=null;
                if(json.borrowerAddressList[index].addressTypeId==1){
                    table=$("#currentBorrowerAddressTable")
                }
                if(json.borrowerAddressList[index].addressTypeId==2){
                    table=$("#permanentBorrowerAddressTable")
                }
                if(json.borrowerAddressList[index].addressTypeId==3){
                    table=$("#previousBorrowerAddressTable")
                }
                if(table!=null){
                    $('input[name="address"]', table).val(json.borrowerAddressList[index].address);
                    $('input[name="postalCode"]', table).val(json.borrowerAddressList[index].postalCode);
                    $('select[name="addressStatus"]', table).val(json.borrowerAddressList[index].addressStatus);
                    $('select[name="addressAreaId"]', table).val(json.borrowerAddressList[index].areaId);
                    $('select[name="yearsOfStay"]', table).val(json.borrowerAddressList[index].yearsOfStay);
                    $('input[name="lotArea"]', table).val(json.borrowerAddressList[index].lotArea);
                    $('input[name="landClass"]', table).val(json.borrowerAddressList[index].landClass);
                    $('input[name="floorArea"]', table).val(json.borrowerAddressList[index].floorArea);
                    $('input[name="stability"]', table).val(json.borrowerAddressList[index].stability);
                    $('input[name="model"]', table).val(json.borrowerAddressList[index].model);
                    $('input[name="make"]', table).val(json.borrowerAddressList[index].make);
                    $('input[name="monthlyRental"]', table).val(json.borrowerAddressList[index].monthlyrental);
                    $('input[name="nameOfOwner"]', table).val(json.borrowerAddressList[index].landLordId);
                }
            }
        }
    }
    if(document.getElementById("borrowerAddress") !=null && json.borrowerAddressList !=null){
        for(var index=0; index < json.borrowerAddressList.length; index++){
            if(json.borrowerAddressList[index].addressTypeId==1){
                $("#borrowerAddress").val(json.borrowerAddressList[index].address);
                $("#addressAreaId").val(json.borrowerAddressList[index].areaId);
            }
        }
    }
    
    if(json.businessList != null && document.getElementById("businessTable") !=null){
        clearTable("businessTable");
        while($("#businessTable tr").length - 1 < json.businessList.length){
            cloneTableRow("businessTable");
        }
        //        if($("#businessTable tr").length == 1){
        //            $('input[name="businessSales2"]').disabled, element).val(json.businessList[1].businesSales2);
        //        }
        if(json.businessList.length > 0){
            $("#businessTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="businessId"]', element).val(json.businessList[index - 1].businessId);
                    $('input[name="businessName"]', element).val(json.businessList[index - 1].businessName);
                    $('input[name="businessType"]', element).val(json.businessList[index - 1].businessType);
                    $('input[name="businessStatus"]', element).val(json.businessList[index - 1].businessStatus);
                    $('input[name="businessAddress"]', element).val(json.businessList[index - 1].businessAddress);
                    $('input[name="businessAddressStatus"]', element).val(json.businessList[index - 1].businessAddressStatus);
                    $('input[name="businessExistence"]', element).val(json.businessList[index - 1].businessExistence);
                    $('input[name="businessPermitNo"]', element).val(json.businessList[index - 1].businessPermitNumber);
                    $('input[name="businessExpiryDate"]', element).val(json.businessList[index - 1].businessPermitExpiryDate);
                    
                    $("#businessSales"+index).val(json.businessList[index - 1].businesSales);
                    $("#businessGoodsSold"+index).val(json.businessList[index - 1].busineeCostOfGoodsSold);
                    $("#businessGross"+index).val(json.businessList[index - 1].businessGrossMonthlyIncome);
                }
            });
        }
    }
            
}
function populateLoanApplicationInfo(json){
    populateLoanApplicationBorrowerInfo(json);
    populateDocumentInfo(json);

    if(json.incomeStatementList != null ){
        if(json.incomeStatementList.length > 0){
            //income statement
            //            $("#businessSalesTotal").val(json.incomeStatementList[0].businessSalesTotal);
            //            $("#businessGoodsTotal").val(json.incomeStatementList[0].businessGoodsTotal);
            //            $("#businessGrossTotal").val(json.incomeStatementList[0].businessGrossIncomeTotal);
            $("#totalIncomeEmployment").val(json.incomeStatementList[0].employmentIncome);
            $("#totalInwardRemittance").val(json.incomeStatementList[0].inwardRemittanceIncome);
            $("#totalOthers").val(json.incomeStatementList[0].otherIncome);
            $("#totalOtherIncome").val(json.incomeStatementList[0].totalOtherIncome);
            
            $("#salariesAndWages").val(json.incomeStatementList[0].businessSalary);
            $("#rent").val(json.incomeStatementList[0].businessRent);
            $("#utilities").val(json.incomeStatementList[0].businessUtilities);
            $("#incidentalExpenses").val(json.incomeStatementList[0].businessIncidentalExpenses);
            $("#taxesAndLicenses").val(json.incomeStatementList[0].businessTaxesLicenses);
            $("#transportation").val(json.incomeStatementList[0].businessTransportation);
            $("#insurance").val(json.incomeStatementList[0].businessInsurance);
            
            $("#totalOperatingExpenses").val(json.incomeStatementList[0].totalOperatingExpenses);
            
            $("#familyRental").val(json.incomeStatementList[0].familyRental);
            $("#familyUtilities").val(json.incomeStatementList[0].familyUtilities);
            $("#familyFood").val(json.incomeStatementList[0].familyFood);
            $("#familyClothing").val(json.incomeStatementList[0].familyClothing);
            $("#familyEducation").val(json.incomeStatementList[0].familyEducation);
            $("#familyMortgage").val(json.incomeStatementList[0].familyMortgage);
            $("#familyMedicine").val(json.incomeStatementList[0].familyMedicine);
            $("#familyInsurance").val(json.incomeStatementList[0].familyInsurance);
            $("#familyOtherLoans").val(json.incomeStatementList[0].familyOtherLoans);
            
            $("#totalFamilyExpenses").val(json.incomeStatementList[0].totalFamilyExpenses);
            
            $("#totalExpenses").val(json.incomeStatementList[0].totalExpenses);
            $("#netDisposableIncome").val(json.incomeStatementList[0].netDisposableIncome);
            $("#maximumLoanToAvail").val(json.incomeStatementList[0].maxLoanToAvail);
            
            
            $("#equipment").val(json.incomeStatementList[0].equipment);
            $("#stocks").val(json.incomeStatementList[0].stocks);
            $("#stockWorth").val(json.incomeStatementList[0].stocksWorth);
            $("#totalEquipment").val(json.incomeStatementList[0].totalEquipment);
            $("#totalStocks").val(json.incomeStatementList[0].totalStocks);
            $("#totalStockWorth").val(json.incomeStatementList[0].totalStocksWorth);
            updateTotals();
        }
    }
   
            
    //other loans
    clearTable("otherLoansTable");
    if(json.otherLoanList != null){
        
        while($("#otherLoansTable tr").length - 1 < json.otherLoanList.length){
            cloneTableRow("otherLoansTable");
        }
        if(json.otherLoanList.length > 0){
            $("#otherLoansTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="otherLoansId"]', element).val(json.otherLoanList[index - 1].otherLoansId);
                    $('input[name="creditorName"]', element).val(json.otherLoanList[index - 1].creditorName);
                    $('input[name="creditorAddress"]', element).val(json.otherLoanList[index - 1].creditorAddress);
                    $('input[name="otherLoanBalance"]', element).val(json.otherLoanList[index - 1].otherLoanBalance);
                }
            });
        }
        
    }
    clearTable("characterReferenceTable");
    if(json.characterReferenceList.length  != null){
        while($("#characterReferenceTable tr").length - 1 < json.characterReferenceList.length){
            cloneTableRow("characterReferenceTable");
        }
        if(json.characterReferenceList.length > 0){
            $("#characterReferenceTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="characterReferenceId"]', element).val(json.characterReferenceList[index - 1].characterReferenceId);
                    $('input[name="characterReferenceFirstName"]', element).val(json.characterReferenceList[index - 1].firstName);
                    $('input[name="characterReferenceMiddleName"]', element).val(json.characterReferenceList[index - 1].middleName);
                    $('input[name="characterReferenceLastName"]', element).val(json.characterReferenceList[index - 1].lastName);
                    $('input[name="characterReferenceAddress"]', element).val(json.characterReferenceList[index - 1].address);
                    $('input[name="characterReferenceContactNo"]', element).val(json.characterReferenceList[index - 1].contactNumber);
                }
            }); 
        }
        
    }
      
    if(json.coBorrowerList  != null){
        if(json.coBorrowerList.length > 0){
            $("#coBorrowerFirstName").val(json.coBorrowerList[0].firstName);
            $("#coBorrowerMiddleName").val(json.coBorrowerList[0].middleName);
            $("#coBorrowerLastName").val(json.coBorrowerList[0].lastName);
            $("#coBorrowerAddress").val(json.coBorrowerList[0].address);
            $("#coBorrowerOccupation").val(json.coBorrowerList[0].occupation);
            $("#coBorrowerGrossIncome").val(json.coBorrowerList[0].grossIncome);
            $("#coBorrowerContactNumber").val(json.coBorrowerList[0].contactNumber);
            $("#coBorrowerSpouseName").val(json.coBorrowerList[0].spouseName);
             
            $("#coBorrowerBusinessName").val(json.coBorrowerList[0].businessName);
            $("#coBorrowerBusinessType").val(json.coBorrowerList[0].businessType);
            $("#coBorrowerBusinessStatus").val(json.coBorrowerList[0].businessStatus);
            $("#coBorrowerBusinessAddress").val(json.coBorrowerList[0].businessAddress);
            $("#coBorrowerBusinessAddressStatus").val(json.coBorrowerList[0].businessStatus);
            $("#coBorrowerBusinessExistencesinYears").val(json.coBorrowerList[0].businessExistenceInYears);
            $("#coBorrowerBusinessPermit").val(json.coBorrowerList[0].businessPermitNo);
            $("#coBorrowerBusinessExpiryDate").val(json.coBorrowerList[0].businessExpiryDate);
        }
    }
            
    //requirements
    clearForm("#backgroundCheckTable");
    if(json.backgroundCheckList  != null){
        for(var index=0; index < json.backgroundCheckList.length; index++){
            setCheckbox("#backgroundCheckTable", json.backgroundCheckList[index].backgorundInvestigationId);
        }
        $("#backgroundCheckRemarks").val(json.backgroundCheckRemarks);
    }
    
    clearForm("#requirementsTable");
    if(json.requirementList  != null){
        for(var i = 0; i < json.requirementList.length; i++){
            setCheckbox("#requirementsTable", json.requirementList[i].requirementId);
        }
    }
    
    
    clearTable("documentPresentedTable");
    if(json.documentsPresentedList.length  != null){
        
        while($("#documentPresentedTable tr").length - 1 < json.documentsPresentedList.length){
            cloneTableRow("documentPresentedTable");
        }
        if(json.documentsPresentedList.length > 0){
            $("#documentPresentedTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="documentPresentedId"]', element).val(json.documentsPresentedList[index - 1].documentsPresentedId);
                    $('input[name="documentPresentedType"]', element).val(json.documentsPresentedList[index - 1].documentType);
                    $('input[name="documentPresentedNumber"]', element).val(json.documentsPresentedList[index - 1].documentNumber);
                    $('input[name="documentPresentedCopy"]', element).val(json.documentsPresentedList[index - 1].documentCopy);
                }
            });
        }
        
    }
    
    if(json.borrowerSpouseList.length != null){
        if(json.borrowerSpouseList.length > 0){
            $("#spouseId").val(json.borrowerSpouseList[0].relativeId);
            $("#spouseFirstName").val(json.borrowerSpouseList[0].firstName);
            $("#spouseProvincialAddress").val(json.borrowerSpouseList[0].address);
            $("#spouseMiddleName").val(json.borrowerSpouseList[0].middleName);
            $("#spouseEducationalAttainment").val(json.borrowerSpouseList[0].educationalAttainment);
            $("#spouseLastName").val(json.borrowerSpouseList[0].lastName);
            $("#spouseOccupation").val(json.borrowerSpouseList[0].occupation);
            $("#spouseDateOfBirth").val(json.borrowerSpouseList[0].dateOfBirth);
            $("#spouseMonthlySalary").val(json.borrowerSpouseList[0].monthlyIncome);
            $("#spousePlaceOfBirth").val(json.borrowerSpouseList[0].placeOfBirth);
            $("#spouseEmployer").val(json.borrowerSpouseList[0].employer);
            $("#spouseCitizenship").val(json.borrowerSpouseList[0].citizenship);
            $("#spouseEmployerAddress").val(json.borrowerSpouseList[0].employerAddress);
            $("#spouseYearsTogether").val(json.borrowerSpouseList[0].yearsTogether);
            $("#spouseEmployerPhoneNo").val(json.borrowerSpouseList[0].employerPhoneNo);
        }
    }
    
}//populate loan application
function populateLoanRequestInfo(json){
    populateBorrowerInfo(json);
    populateDocumentInfo(json);
    populateReferenceDocumentInfo(json);
            
    //monthly statement
    //    $("#monthlyStatementBusinessIncome").val(json.monthlyStatementList[0].businessIncome);
    //    $("#monthlyStatementEmploymentIncome").val(json.monthlyStatementList[0].employmentIncome);
    //    $("#monthlyStatementSpouseIncome").val(json.monthlyStatementList[0].spouseIncome);
    //    $("#monthlyStatementOtherIncome").val(json.monthlyStatementList[0].otherIncome);
    //    $("#monthlyStatementEducationExpense").val(json.monthlyStatementList[0].educationExpense);
    //    $("#monthlyStatementFoodAndClothingExpense").val(json.monthlyStatementList[0].foodAndClothingExpense);
    //    $("#monthlyStatementRentExpense").val(json.monthlyStatementList[0].rentExpense);
    //    $("#monthlyStatementOutstandingLoanExpense").val(json.monthlyStatementList[0].outstandingLoanExpense);
    //    updateTotals();
    //            
    //    //other loans
    //    clearTable("otherLoansTable");
    //    if(json.otherLoanList.length > 0){
    //        while($("#otherLoansTable tr").length - 1 < json.otherLoanList.length){
    //            cloneTableRow("otherLoansTable");
    //        }
    //        $("#otherLoansTable tr").each(function(index,element){
    //            if(index > 0){
    //                $('input[name="otherLoansId"]', element).val(json.otherLoanList[index - 1].otherLoansId);
    //                $('input[name="creditorName"]', element).val(json.otherLoanList[index - 1].creditorName);
    //                $('input[name="creditorAddress"]', element).val(json.otherLoanList[index - 1].creditorAddress);
    //                $('input[name="otherLoanBalance"]', element).val(json.otherLoanList[index - 1].otherLoanBalance);
    //            }
    //        });
    //    }
    //    clearTable("characterReferenceTable");
    //    if(json.characterReferenceList.length > 0){
    //        while($("#characterReferenceTable tr").length - 1 < json.characterReferenceList.length){
    //            cloneTableRow("characterReferenceTable");
    //        }
    //        $("#characterReferenceTable tr").each(function(index,element){
    //            if(index > 0){
    //                $('input[name="characterReferenceId"]', element).val(json.characterReferenceList[index - 1].characterReferenceId);
    //                $('input[name="characterReferenceFirstName"]', element).val(json.characterReferenceList[index - 1].firstName);
    //                $('input[name="characterReferenceMiddleName"]', element).val(json.characterReferenceList[index - 1].middleName);
    //                $('input[name="characterReferenceLastName"]', element).val(json.characterReferenceList[index - 1].lastName);
    //                $('input[name="characterReferenceAddress"]', element).val(json.characterReferenceList[index - 1].address);
    //                $('input[name="characterReferenceOccupation"]', element).val(json.characterReferenceList[index - 1].occupation);
    //            }
    //        });
    //    }
    
    if(json.coBorrowerList.length != null && document.getElementById("coBorrowerTable") !=null){
        clearTable("coBorrowerTable");
        while($("#coBorrowerTable tr").length - 1 < json.coBorrowerList.length){
            cloneTableRow("coBorrowerTable");
        }
        if(json.coBorrowerList.length > 0){
            $("#coBorrowerTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="coBorrowerId"]', element).val(json.coBorrowerList[index - 1].coBorrowerId);
                    $('input[name="coBorrowerFirstName"]', element).val(json.coBorrowerList[index - 1].firstName);
                    $('input[name="coBorrowerMiddleName"]', element).val(json.coBorrowerList[index - 1].middleName);
                    $('input[name="coBorrowerLastName"]', element).val(json.coBorrowerList[index - 1].lastName);
                    $('input[name="coBorrowerAddress"]', element).val(json.coBorrowerList[index - 1].address);
                    $('input[name="coBorrowerContactNumber"]', element).val(json.coBorrowerList[index - 1].contactNumber);
                    $('input[name="coBorrowerOccupation"]', element).val(json.coBorrowerList[index - 1].occupation);
                    $('input[name="coBorrowerGrossIncome"]', element).val(json.coBorrowerList[index - 1].grossIncome);
                }
            });
        }
    }
    if(json.collateralList.length != null && document.getElementById("collateralTable") !=null){
        clearTable("collateralTable");
        while($("#collateralTable tr").length - 1 < json.collateralList.length){
            cloneTableRow("collateralTable");
        }
        if(json.coBorrowerList.length > 0){
            $("#collateralTable tr").each(function(index,element){
                if(index > 0){
                    $('input[name="collateralId"]', element).val(json.collateralList[index - 1].loanApplicationCollateralId);
                    $('input[name="collateralMake"]', element).val(json.collateralList[index - 1].makeAndType);
                    $('input[name="collateralBrand"]', element).val(json.collateralList[index - 1].brand);
                    $('input[name="collateralCondition"]', element).val(json.collateralList[index - 1].generalCondition);
                }
            });
        }
    }
    if(json.creditMatrix != null && document.getElementById("loanApplicationCreditRating") !=null){
        $("#loanApplicationCreditRating").val(json.creditMatrix.creditRating);
    }
            
//requirements
//    clearForm("#requirementsTable");
//    if(json.requirementList.length > 0){
//        for(var index=0; index < json.requirementList.length; index++){
//            setCheckbox("#requirementsTable", json.requirementList[index].requirementId);
//        }
//    }
}//populate loan application
function promptJSONMessage(dialogId,json){
    var actionMessages="";
    var actionErrors="";
    if(json.actionMessages != null){
        actionMessages="<ul  class=\"actionMessage\">\n";
        for(var ctr=0;ctr < json.actionMessages.length;ctr++){
            actionMessages+="<li>"+json.actionMessages[ctr]+"</li>\n";
        }
        actionMessages += "</ul>\n";
    }
   
    if(json.actionErrors != null){
        actionErrors="<ul  class=\"errorMessage\">\n";
        for(ctr=0;ctr < json.actionErrors.length;ctr++){
            actionErrors+="<li>"+json.actionErrors[ctr]+"</li>\n";
        }
        actionErrors += "</ul>\n";   
    }                
    
                    
    $(dialogId).html(actionErrors+actionMessages);
    $(dialogId).dialog('open');
}//promptJSONMessage

function promptMessage(dialogId,message){
    $(dialogId).html(message);
    $(dialogId).dialog({
        buttons: [

        {
            text: "Ok",
            click: function() {
                status= 1;
                $(this).dialog("close");
                
            }
            
        }
        ]
    });
    $(dialogId).dialog('open');
}

function promptMessage(dialogId,message){
    $(dialogId).html(message);
    $(dialogId).dialog({
        buttons: [

        {
            text: "Ok",
            click: function() {
                status= 1;
                $(this).dialog("close");
                
            }
            
        },
        {
            text: "Cancel",
            click: function() {
                status= 1;
                $(this).dialog("close");
                
            }
            
        }
        ]
    });
    $(dialogId).dialog('open');
}

$(document).ready(function(){
//    updateClock();
//    setInterval('updateClock()',1000);
//    $('#mainNavigation > li > a').click(function () {
//        var divname= this.name;
//        $("#"+divname).show("slow").siblings().hide("slow");
//        $('#mainNavigation > li > a > span').removeClass("main-menu-highlight");
//        $("#"+this.id+" > span").addClass("main-menu-highlight");
//    });
    $("#cancelChangePassword").click(function(){
        window.location="index";       
    });
    $("#changePassword").click(function(){
        $("#changeEmployeeAuthenticationForm").submit();  
    });
});


